package host.skiree.nettydemo.client;

import host.skiree.nettydemo.client.handler.DemoRpcClientHandler;
import host.skiree.nettydemo.message.RpcRequestMessage;
import host.skiree.nettydemo.protocol.MessageCodecSharable;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @author gcl
 * @date 2022/9/27 9:13
 */
@Slf4j
public class NettyRpcClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            Channel channel = new Bootstrap()
                    .group(workGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(10240, 11,4,1,0));
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new MessageCodecSharable());
                            ch.pipeline().addLast(new DemoRpcClientHandler());
                        }
                    })
                    .connect(new InetSocketAddress("127.0.0.1", 8088))
                    .sync()
                    .channel();
            // 发送消息
            ChannelFuture future = channel.writeAndFlush(new RpcRequestMessage(
                    1,
                    "host.skiree.nettydemo.service.HelloService",
                    "sayHello",
                    String.class,
                    new Class[]{String.class},
                    new Object[]{"张三"}
            )).addListener(promise -> {
                if (!promise.isSuccess()) {
                    Throwable cause = promise.cause();
                    log.error("error", cause);
                }
            });
            channel.closeFuture().sync();
        }finally {
            workGroup.shutdownGracefully();
        }

    }
}
